<template>
	<div>
		<div class="wrapper-container">
			<div class="wrapper-row" :class="{ 'wrapper-row-active': item.isActive }" v-for="(item, index) in curNodeList" :key="index" @click="scrollToSection(item.id)">
				{{ item.name }}
			</div>
		</div>
	</div>
</template>

<script setup>
	import { scrollToSection } from '@/utils/publicUtils';
	import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
	// 接收2个参数：第二个参数可以自定义距离顶部高度，默认是200，无特殊情况，可以不传
	const props = defineProps({
		nodeList: { type: Array }, // [{name: '基本信息', id: 'xxx'}]
		marginTop: { type: Number, default: 200 },
	});

	watch(
		() => props.nodeList,
		newVal => {
			curNodeList.value = newVal.map((item, index) => {
				return {
					name: item.name,
					id: item.id,
					top: 0,
					isActive: index == 0 ? true : false,
				};
			});
		},
		{ deep: true },
	);

	// jhy修改reactive不能绑定基础类型
	const curMarginTop = ref(props.marginTop);
	let curNodeList = ref([]);
	props.nodeList.map((item, index) => {
		curNodeList.value.push({
			name: item.name,
			id: item.id,
			top: 0,
			isActive: index == 0 ? true : false,
		});
	});

	const handleScroll = () => {
		// 需要找到最后一个<100的锚点，为当前的active, 因此需要倒序处理一下
		const copyList = JSON.parse(JSON.stringify(curNodeList.value)).reverse();
		let hasActive = false;
		copyList.map(item => {
			item.top = document.getElementById(item.id).getBoundingClientRect().top;
			if (item.top < curMarginTop.value && !hasActive) {
				item.isActive = true;
				hasActive = true;
			} else {
				item.isActive = false;
			}
		});
		curNodeList.value = copyList.reverse();
	};

	onMounted(() => {
		window.addEventListener('scroll', handleScroll, true);
	});
	onBeforeUnmount(() => {
		if (curNodeList.value.length > 0) {
			scrollToSection(curNodeList.value[0].id); // 卸载前滚动到顶部---jhy
		}
		window.removeEventListener('scroll', handleScroll, true); // 离开当前组件别忘记移除事件监听
	});
</script>
<script>
	export default { name: 'hsDocWrapper' };
</script>

<style scoped>
	.wrapper-container {
		border-left: 2px solid #dedede;
	}

	.wrapper-row {
		padding-left: 20px;
		margin-bottom: 20px;
		margin-left: -2px;
		border-left: 2px solid #dedede;
		color: #666666;
		cursor: pointer;
		white-space: nowrap;
		min-width: 100px;
		box-sizing: border-box;
	}

	.wrapper-row-active {
		border-left: 2px solid #477afd;
		margin-left: -2px;
		color: #477afd;
	}
</style>
